package ms.unicorn.language.languagedef;

import ms.unicorn.util.ErrorHandler;
import ms.unicorn.util.ReflectionUtil;

public class LanguageDefUtil {
	
	@SuppressWarnings("unchecked")
	public static <T> T resolveDefinition(XReferenceExpression exp) {
		return (T) (exp.isNewInstance()? exp.getDefinition() : exp.getReference()); 
	}
	
	public static Class<?> resolveImplClass(Object def) {
		String className = ReflectionUtil.getPropertyValue(def, "Clazz", null);
		Class<?> clazz = ReflectionUtil.getClass(className);
		if (clazz == null) {
			Object superElement = ReflectionUtil.getPropertyValue(def, "SuperElement", null);
			if (superElement != null)
				clazz = resolveImplClass(superElement);
		}
		return clazz;
	}
	
	public static Class<?> resolveImplClass(Object def, Class<?> defaultClass) {
		Class<?> clazz = resolveImplClass(def);
		return clazz != null ? clazz : defaultClass;
	}
	
	@SuppressWarnings("unchecked")
	public static <T> T createFromDefinition(ModuleItem item, Class<?> defaultClass) {
		Class<?> clazz = resolveImplClass(item, defaultClass);
		if (clazz != null) {
			try {
				Object ins = clazz.newInstance();
				TagDef properties = TagDefUtil.getProperties(item);
				if (properties != null)
					TagDefUtil.setProperties(ins, properties.getEntry());
				return (T)ins;
			} catch (Exception e) {
				ErrorHandler.handleException(e);
			}
		}
		return null;
	}
}
